package com.github.doobo.handler;

import com.alibaba.fastjson.JSON;
import com.github.doobo.bo.IpfsNodeInfo;
import com.github.doobo.bo.PubMessageBO;
import com.github.doobo.bo.PubMsgEncodeBO;
import com.github.doobo.utils.OsUtils;
import com.github.doobo.utils.WordUtils;
import com.github.doobo.vbo.ResultTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 添加节点配置
 *
 * @Description: ipfs-cloud
 * @User: diding
 * @Time: 2022-12-19 17:53
 */
@Slf4j
@Component
public class PlatformBootstrapHandler extends AbstractPlatformMsgHandler {

	public boolean isMatchBody(PubMessageBO body){
		if(Objects.isNull(body)){
			return false;
		}
		IpfsNodeInfo info = AbstractPlatformInitHandler.RESPONSE.getInfo();
		if(Objects.isNull(info)){
			return false;
		}
		return "ipfs/addBootstrap/callback".equals(body.getUri())
			&& Objects.equals(info.getCid(), body.getTarget())
			&& !Objects.equals(info.getCid(), body.getFrom());
	}

	@Override
	public void handler(PubMessageBO body, PubMsgEncodeBO msg) {
		if(!isMatchBody(body)){
			return;
		}
		List<IpfsNodeInfo> infoList = JSON.parseArray(body.getBody(), IpfsNodeInfo.class);
		if(CollectionUtils.isEmpty(infoList)){
			log.info("addBootstrap list is empty.");
			return;
		}
		List<IpfsNodeInfo> infos = infoList.stream().filter(Objects::nonNull)
			.map(m -> {
				if (Objects.isNull(m.getPort()) || Objects.isNull(m.getIp())) {
					log.info("ip or port is null:{}", m);
					return null;
				}
				if (!OsUtils.checkIpPortOpen(m.getIp(), m.getPort())) {
					log.info("ip and port is not open:{}", m);
					return null;
				}
				if (m.getIp().contains("localhost") || m.getIp().contains("127.0")) {
					log.info("ip is localhost address:{}", m);
					return null;
				}
				String ipfs;
				if (WordUtils.isIpV4Address(m.getIp())) {
					ipfs = String.format("/ip4/%s/tcp/%s/ipfs/%s", m.getIp(), m.getPort(), m.getCid());
				} else {
					ipfs = String.format("/dnsaddr/%s/tcp/%s/ipfs/%s", m.getIp(), m.getPort(), m.getCid());
				}
				m.setAddress(Collections.singletonList(ipfs));
				return m;
			}).filter(Objects::nonNull).collect(Collectors.toList());
		ResultTemplate<Boolean> template = AbstractPlatformInitHandler.addBootstrapList(infos);
		Optional.ofNullable(template).filter(f -> !f.isSuccess())
			.ifPresent(c -> log.error("addBootstrapListError:{}", c));
	}
}
